import io
import json


def paserParamList(oValue):

    # todo 智能获取参数变量
    params = {}
    for op in oValue:
        params[op['name']] = op['description'] if 'description' in op else ''
    return params


def parserHeaders(oheader, omethod):
    headers = {}
    pType = 'params'
    if 'consumes' in oheader:
        headers['Content-Type'] = ','.join(v for v in oheader['consumes'])
        pType = 'params' if omethod == 'get' else \
            ('data' if 'form-data' in headers['Content-Type'] else 'json')
        # pType = 'json' if 'json' in headers['Content-Type'] else \
        #     ('data' if 'form-data' in headers['Content-Type'] else 'params')

    headers['Authorization'] = '$token'
    return headers, pType


def parserSwagValue(oValue, id, url):
    oApi = {}
    tag = ''
    oApi['id'] = id

    xmethod = 'get' if 'get' in oValue else \
        ('post' if 'post' in oValue else \
             ('put' if 'put' in oValue else 'delete'))
    oApi['name'] = url
    oApi['desc'] = oValue[xmethod]['summary']

    oApi['request'] = {}

    oApi['request']['method'] = xmethod.upper()
    tag = oValue[xmethod]['tags'][0]

    oApi['request']['url'] = url

    # 根据header中 consume ，获取参数类型：params/data/json
    oApi['request']['headers'], ptype = parserHeaders(oValue[xmethod], xmethod)

    if 'parameters' in oValue[xmethod]:
        oApi['request'][ptype] = paserParamList(oValue[xmethod]['parameters'])

    oApi['validate'] = [{"eq": ['status_code', 200]},
                        {"eq": ['headers.Content-Type', 'application/json']}]
    oApi['extract'] = {}

    oApi['tag'] = tag

    return oApi, tag


def dictAppendlist(xdict, tag, ovalue):
    if tag not in xdict:
        xdict[tag] = []
    xdict[tag].append(ovalue)


def listAppend(xlist, ovalue):
    xlist.append(ovalue)


def loadSwaggerFile(filename):
    with io.open(filename, 'r', encoding='utf-8') as jfile:
        jSwag = json.load(jfile)
    # print(jSwag['paths'])

    ApiList = []
    i = 1
    for xKey, xValue in jSwag['paths'].items():
        # print(str(i) + ' = ' + xKey)

        oApi, tag = parserSwagValue(xValue, i, xKey)

        listAppend(ApiList, oApi)

        # dictAppendlist(ApiDict, tag, oApi)
        # print(oApi)
        i += 1

    ApiDict = {"config": {
        "name": "testcase description",
        "base_url": '',
        "variables": {
            "user": '524',
            "password": '111111',
            "token": 1
        },
    },
        "teststeps": ApiList
    }

    return ApiDict


def load():
    filename = 'E:/downloads/swaggerApi (6).json'

    ApiDict = loadSwaggerFile(filename)

    print(json.dumps(ApiDict, skipkeys=False, check_circular=True, allow_nan=True,
                     indent=4, separators=(',', ':'), ensure_ascii=False))

    # json2File('d:\kkkk.json', ApiDict)


if __name__ == "__main__":
    load()
